<template>
  <view class="UpdatePlanTask">
    <!-- 标题框 -->
    <view class="inputContent content">
      <text class="title">标题</text>
      <input
        type="text"
        class="inputBox"
        placeholder="请输入任务名"
        placeholder-style="font-size: 26rpx;margin-left:10rpx"
        v-model="taskContent.title"
      />
    </view>

    <!-- 任务框 -->
    <view class="taskContent content">
      <text class="title">步骤</text>
      <view class="taskBox">
        <template v-if="taskContent.steps.length">
          <view
            class="stepBox"
            v-for="(item, index) in taskContent.steps"
            :key="index"
          >
            <view class="checkBox" @click="handleCheckTask(index)">
              <image
                src="../../static/icons/check.png"
                class="checkIcon"
                v-if="item.finished"
              ></image>
            </view>
            <input
              type="text"
              class="stepInput"
              placeholder="请输入步骤"
              placeholder-style="font-size: 26rpx;margin-left:10rpx"
              v-model="item.value"
            />
            <view @click="removeStep(index)" class="removeStep">x</view>
          </view>
        </template>
        <view class="next" @click="addTask">
          <text class="addSign">+</text>
          <text>下一步</text>
        </view>
      </view>
    </view>

    <!-- 描述框 -->
    <view class="describeContent content">
      <text class="title">描述</text>
      <view style="flex: 1">
        <MyRichTextEditor
          ref="myEditorRef"
          :currentEditorHtml="taskContent.describe"
        />
      </view>
    </view>
    <!-- 附件上传 -->
    <view class="fileContent content">
      <text class="title">附件</text>
      <view style="flex: 1">
        <MyUploader ref="myUploaderRef" :fileList="taskContent.fileList" />
      </view>
    </view>

    <!-- 分配任务栏 -->
    <view class="stepshareContent content" v-if="!taskContent.isMe">
      <text :class="['title', taskContent.isAlloc.length ? 'allocTitle' : '']"
        >分配任务</text
      >
      <view class="shareContent">
        <!-- 分配给组员 -->
        <view class="shareBox" v-if="taskContent.teamInfo.isTeam">
          <view class="shareTip">
            <image src="../../static/icons/share.png" class="shareIcon"></image>
            <view class="share">{{
              taskContent.isAlloc.length ? "已分配给" : "分配给"
            }}</view>
          </view>
          <view
            class="teamUser"
            @click="showTeamUserList"
            v-if="!taskContent.isAlloc.length"
          >
            <view class="chooseName">{{ chooseTaskUser.nickName }}</view>
            <image
              src="../../static/icons/arrow.png"
              :class="['arrow', isOpenList ? 'arrowActive' : '']"
            ></image>
            <view :class="['options', isOpenList ? 'optionsActive' : '']">
              <scroll-view scroll-y="true" style="height: 100%">
                <view
                  class="optionItem animate__animated animate__bounceInRight"
                  v-for="(item, index) in teamMember"
                  :key="index"
                  @click.stop="getChooseUser(item)"
                >
                  <image :src="item.avatar" class="avatar"></image>
                  <view class="nickName">{{ item.nickName }}</view>
                </view>
              </scroll-view>
            </view>
          </view>
          <view class="allocMember" v-else>
            <image :src="isAllocUser.avatar" class="avatar"></image>
            <view class="nickName">{{ isAllocUser.nickName }}</view>
          </view>
        </view>

        <!-- 生成分享码 -->
        <view class="shareBox">
          <view class="shareTip" @click="handleShareCode">
            <image
              src="../../static/icons/shareCode.png"
              class="shareCodeIcon"
            ></image>
            <view class="share">生成分享码</view>
          </view>
          <view class="code" @click="copyToBoard">{{
            taskContent.allocCode
          }}</view>
        </view>
      </view>
    </view>

    <!-- 选择日期框 -->
    <view class="dateContent content">
      <view class="dateBox">
        <text class="title">截止日期</text>
        <view class="dateInput">
          <image src="../../static/icons/calendar.png" class="dateIcon"></image>
          <view class="date">
            <view @click="showDateBox(0)">{{ getTime(0) }}</view>
            <view class="clear" @click="clearTime(0)">x</view>
          </view>
        </view>
      </view>
      <view class="dateBox">
        <text class="title">提醒时间</text>
        <view class="dateInput">
          <image src="../../static/icons/calendar.png" class="dateIcon"></image>
          <view class="date">
            <view @click="showDateBox(1)">{{ getTime(1) }}</view>
            <view class="clear" @click="clearTime(1)">x</view>
          </view>
        </view>
      </view>
    </view>

    <!-- 选择日期 -->
    <van-calendar
      :show="showCalendar"
      @close="showCalendar = false"
      @confirm="confirmCalendar"
      color="#05A47D"
    />
    <!-- 选择具体时间段 -->
    <van-popup :show="showDate" position="bottom">
      <van-datetime-picker
        type="time"
        :value="getHHMM"
        :min-hour="new Date().getHours()"
        :max-hour="24"
        @confirm="confirmPickTime"
        @cancel="showDate = false"
        title="选择提醒时间"
      />
    </van-popup>

    <van-button
      block
      round
      color="#05A47D"
      class="btnSumbit"
      @click="handleSumbit"
      :disabled="taskContent.isTime || btnLoading"
      >{{ taskContent.isTime ? "已超过截止日期" : "确认修改" }}</van-button
    >
  </view>
</template>

<script>
import { TaskMessage } from "../../utils/messageController.js";
import { mapState } from "vuex";
import MyRichTextEditor from "../../components/planTask/MyRichTextEditor.vue";
import MyUploader from "../../components/planTask/MyUploader.vue";
import { env } from "../../config.js";
export default {
  name: "UpdatePlanTask",
  components: {
    MyRichTextEditor,
    MyUploader,
  },
  data() {
    return {
      taskContent: {},
      chooseTaskUser: {},
      isAllocUser: {},
      steps: [],
      showDate: false,
      showCalendar: false,
      isOpenList: false,
      btnLoading: false,
      chooseTime: "",
      timeType: 0, // 0设置截至时间 1设置提醒时间日期
      dateContent: [
        {
          content: "设置日期",
          time: "",
        },
        {
          content: "设置提醒时间",
          time: "",
        },
      ],
    };
  },
  computed: {
    ...mapState(["userInfo", "taskTeam", "teamMember"]),

    getTime() {
      return function (index) {
        return this.dateContent[index].time.length
          ? this.dateContent[index].time
          : this.dateContent[index].content;
      };
    },
    getHHMM() {
      let hour = new Date().getHours(),
        minute = new Date().getMinutes();
      minute = minute >= 10 ? minute : "0" + minute;
      return hour + ":" + minute;
    },
  },

  onLoad: function (options) {
    this.taskContent = JSON.parse(decodeURIComponent(options.taskDetail));
    this.initData();
  },

  methods: {
    // 初始化数据
    async initData() {
      if (this.taskContent.teamInfo.isTeam) {
        this.getTaskTeamDetail();
      }
      if (!!this.taskContent.endTime.length)
        this.dateContent[0].time = this.$formatTime.formatTimeToHHMM(
          this.taskContent.endTime
        );
      if (!!this.taskContent.remindTime.length)
        this.dateContent[1].time = this.$formatTime.formatTimeToHHMM(
          this.taskContent.remindTime
        );
      // 任务已经分配出去，则不能再次分配
      if (this.taskContent.isAlloc.length) {
        const userId = this.taskContent.isAlloc;
        await this.$store.dispatch("getUserInfo", { userId, type: 2 });
        this.isAllocUser = this.teamMember[0];
      }
    },
    // 确认时间
    confirmPickTime(e) {
      console.log(e.detail);
      this.chooseTime += " " + e.detail;
      this.showDate = false;
      this.dateContent[this.timeType].time = this.chooseTime;
      this.taskContent.remindTime = new Date(this.chooseTime);
      console.log("选择时间:", this.chooseTime);
    },

    // 确认日期
    confirmCalendar(e) {
      this.chooseTime = this.$formatTime.formatTime(e.detail);
      // 设置提醒时间
      if (this.timeType) {
        console.log(e.detail);
        this.showCalendar = false;
        this.showDate = true;
      } else {
        // 设置日期
        console.log(e.detail);
        this.dateContent[this.timeType].time = this.chooseTime;
        this.taskContent.endTime = e.detail;
        this.showCalendar = false;
      }
    },

    // 提交信息
    async handleSumbit() {
      this.btnLoading = true;
      if (this.validForm()) {
        const steps = this.taskContent.steps;
        this.taskContent.isFinish = steps.every((item) => item.finished);
        try {
          const fileList = await this.composeUploadFile();
          if (this.taskContent.fileList.length) {
            fileList.forEach((item) => {
              this.taskContent.fileList.push(item);
            });
          }else{
            this.taskContent.fileList = fileList;
          } 
          this.taskContent.describe = await this.handleGetEditorContent(); // 描述信息
          this.allocTaskToUser();
          await this.$store.dispatch(
            "m_task/updateTaskDetail",
            this.taskContent
          );
          this.$store.commit("m_task/clearTaskList"); // 重新获取数据
          await this.getTaskListData();
          uni.navigateBack();
        } catch (err) {
          console.log(err);
          uni.showToast({
            icon: "error",
            title: "修改失败",
          });
        }
      }
      this.btnLoading = false;
    },

    // 获取文件上传后的详细内容
    async composeUploadFile() {
      return new Promise(async (resolve, reject) => {
        try {
          const tempFiles = this.$refs.myUploaderRef.tempFiles;
          // 没有上传列表，直接返回[]
          console.log("checktemp:",tempFiles);
          if (!tempFiles.length) {
            resolve([]);
          }else{
            console.log("123123");
            const result = await this.$refs.myUploaderRef.uploadFileToDB();
            console.log("上传结果：", result);
            const composeFiles = tempFiles.map((item, index) => {
              return {
                author: item.author,
                fileID: result[index].fileID,
                fileName: item.name,
              };
            });
            resolve(composeFiles);
          }

        } catch (err) {
          //TODO handle the exception
          console.log("上传失败：", err);
          reject(err);
        }
      });
    },

    // 获取富文本内容并替换为上传图片
    handleGetEditorContent() {
      return new Promise(async (resolve, reject) => {
        try {
          this.$refs.myEditorRef.getEDitContent().then(async (res) => {
            // env:需要判断图片是不是已在云存储里的图片，如果是则不需要再上传
            const tempPic = this.getEditorContentImg(res.html).filter(item => !item.includes(env));
            const fileList = [];
            if (tempPic.length) {
              // 组合图片文件，进行上传
              tempPic.forEach((item, index) => {
                const fileName =
                  Math.floor(new Date().getTime() / 1000) + "-" + index;
                fileList.push({ fileName, filePath: item });
              });
              const uploadResult = await this.uploadEditorFile(fileList);
              // 上传至云存储将图片地址替换
              uploadResult.forEach((item, index) => {
                res.html = res.html.replace(tempPic[index], item.fileID);
              });
            }
            console.log("replace:", res.html);
            resolve(res.html);
          });
        } catch (err) {
          console.log("重置文本出错：", err);
          reject(err);
        }
      });
    },

    // 匹配出富文本内容里图片的src数组
    getEditorContentImg(html) {
      const images = html.match(/<img.*?(?:>|\/>)/gi); // 匹配出富文本里的img标签
      if (!images) {
        return [];
      }
      // 匹配出src
      let srcArr = images
        .map((str) => {
          if (!str.match(/ src=[\'\"]?([^\'\"]*)[\'\"]?/i)[1].startsWith("/")) {
            return str.match(/ src=[\'\"]?([^\'\"]*)[\'\"]?/i)[1];
          }
        })
        .filter((src) => !!src);
      return srcArr;
    },
    // 上传富文本当中的图片
    async uploadEditorFile(fileList) {
      try {
        const res = await this.$store.dispatch(
          "m_task/uploadTaskEditorImage",
          fileList
        );
        return res;
      } catch (err) {
        console.log("上传出错：", err);
      }
    },

    // 展示队伍成员
    showTeamUserList() {
      if (!this.taskTeam.userList.length) {
        uni.showToast({
          icon: "error",
          title: "该队伍无成员",
        });
        return;
      }
      this.isOpenList = !this.isOpenList;
      this.getTaskTeamUserList();
    },

    // 如果是队伍任务就需要先获取队伍信息
    async getTaskTeamDetail() {
      const teamId = this.taskContent.teamInfo.teamId,
        type = "taskTeam";
      await this.$store.dispatch("getOneUserTeam", { teamId, type });
    },

    // 获取成员的数据
    async getTaskTeamUserList() {
      const userList = this.taskTeam.userList;
      this.$store.commit("clearTeamMember"); // 先将残留队伍成员清空再获取
      for (let i = 0; i < userList.length; i++) {
        const userId = userList[i];
        await this.$store.dispatch("getUserInfo", { type: 2, userId });
      }
    },
    // 获取任务列表数据
    async getTaskListData(page = 0, limitCount = 10) {
      const userId = this.userInfo._openid;
      await this.$store.dispatch("m_task/getTaskList", {
        page,
        limitCount,
        userId,
      });
    },

    // 为队员分配任务发送消息
    async handleSendMessage() {
      const receiveId = this.chooseTaskUser._openid,
        teamName = this.taskTeam.title,
        authorName = this.taskTeam.author.nickName,
        taskName = this.taskContent.title,
        messageItem = new TaskMessage().messageForPublishTask({
          receiveId,
          teamName,
          authorName,
          taskName,
        });
      await this.$store.dispatch("m_message/sendMessage", messageItem);
    },

    // 将任务同时分配给队员
    async allocTaskToUser() {
      if (Object.keys(this.chooseTaskUser).length) {
        const listId = this.chooseTaskUser.allocTask,
          taskId = this.taskContent._id,
          isAlloc = true;
        this.taskContent.isAlloc = this.chooseTaskUser._openid; // 保存分配的队伍人员id
        this.handleSendMessage(); // 为分配的队员发送消息
        await this.$store.dispatch("m_task/addTask", {
          listId,
          taskId,
          isAlloc,
        });
      }
    },

    // 选择分配给的队员
    getChooseUser(item) {
      this.chooseTaskUser = item;
      this.isOpenList = false;
    },
    // 验证表单信息
    validForm() {
      if (!this.taskContent.title.length) {
        uni.showToast({
          icon: "error",
          title: "标题不能为空",
        });
        return false;
      }
      if (!this.taskContent.steps.length) {
        uni.showToast({
          icon: "error",
          title: "未填写步骤",
        });
        return false;
      }
      if (!this.taskContent.endTime.toString().length) {
        uni.showToast({
          icon: "error",
          title: "截止时间未填写",
        });
        return false;
      }
      if (
        new Date(this.taskContent.endTime).getTime() <= new Date().getTime()
      ) {
        uni.showToast({
          icon: "error",
          title: "时间不符合规范",
        });
        return false;
      }
      if (
        this.taskContent.remindTime.toString().length &&
        new Date(this.taskContent.remindTime).getTime() <= new Date().getTime()
      ) {
        uni.showToast({
          icon: "error",
          title: "时间不符合规范",
        });
        return false;
      }
      if (
        this.taskContent.endTime.toString().length &&
        this.taskContent.remindTime.toString().length
      ) {
        const time1 = new Date(this.taskContent.endTime).getTime(),
          time2 = new Date(this.taskContent.remindTime).getTime();
        if (time2 >= time1) {
          uni.showToast({
            icon: "error",
            title: "时间不符合规范",
          });
          return false;
        }
      }
      return true;
    },

    // 添加任务步骤
    addTask() {
      const item = {};
      item.value = "";
      item.finished = false;
      this.taskContent.steps.push(item);
    },

    // 删除指定步骤
    removeStep(index) {
      this.taskContent.steps.splice(index, 1);
    },

    // 打开box，同时需要设置类型
    showDateBox(type) {
      this.timeType = type;
      this.showCalendar = true;
    },

    // 勾选任务是否完成
    handleCheckTask(index) {
      this.taskContent.steps[index].finished =
        !this.taskContent.steps[index].finished;
    },

    // 清空时间内容
    clearTime(type) {
      this.dateContent[type].time = "";
      if (type) {
        this.taskContent.remindTime = "";
      } else {
        this.taskContent.endTime = "";
      }
    },

    // 分享按钮逻辑处理
    handleShareCode() {
      if (!this.taskContent.allocCode.length) {
        this.taskContent.allocCode = this.$uuid();
        uni.showToast({
          icon: "success",
          title: "已生成分享码",
        });
        return;
      }
      uni.showToast({
        icon: "error",
        title: "分享码已存在",
      });
    },
    // 将分享码复制到粘贴板
    copyToBoard() {
      if (this.taskContent.allocCode.length) {
        const data = this.taskContent.allocCode;
        wx.setClipboardData({
          data,
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
page {
  .UpdatePlanTask {
    padding: 20rpx;
    background-color: #fff;
  }
  .content {
    display: flex;
    align-items: center;
    margin: 20rpx 20rpx;
    padding-bottom: 15rpx;
    border-bottom: 1px solid #eef;
    font-size: 34rpx;
    .inputBox {
      width: 75%;
      border-radius: 8rpx;
      height: 65rpx;
      box-shadow: 0 0 5rpx rgba(0, 0, 0, 0.3);
      padding: 5rpx;
      padding-left: 15rpx;
    }
    .title {
      margin-right: 50rpx;
    }
    .allocTitle {
      margin-top: 10rpx;
    }
    .next {
      color: #bbb;
      display: flex;
      align-items: center;
      .addSign {
        font-size: 45rpx;
        margin-right: 15rpx;
      }
    }

    .textBox {
      padding: 20rpx;
      width: 70%;
      height: 200rpx;
      color: #aaa;
      font-size: 30rpx;
    }
  }
  .taskContent {
    align-items: flex-start;
    .title {
      margin-top: 10rpx;
    }
    .stepBox {
      display: flex;
      align-items: center;
      margin-bottom: 20rpx;
      .checkBox {
        position: relative;
        width: 30rpx;
        height: 30rpx;
        border: 3rpx solid #bbb;
        border-radius: 5rpx;
        margin-right: 20rpx;
        .checkIcon {
          position: absolute;
          top: -15rpx;
          left: -6rpx;
          width: 50rpx;
          height: 55rpx;
        }
      }
      .stepInput {
        padding: 5rpx;
        padding-left: 15rpx;
        border-radius: 8rpx;
        height: 60rpx;
        box-shadow: 0 0 5rpx rgba(0, 0, 0, 0.3);
        margin-right: 20rpx;
        color: #aaa;
        font-size: 28rpx;
      }
      .removeStep {
        width: 60rpx;
        font-size: 35rpx;
        color: #bbb;
      }
    }
  }

  .describeContent,
  .fileContent {
    align-items: flex-start;
    .title {
      margin-top: 15rpx;
    }
  }

  .stepshareContent {
    display: flex;
    align-items: flex-start;

    .title {
      margin-right: 20rpx;
    }
    .shareContent {
      flex: 1;
    }
    .shareBox {
      width: 100%;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 30rpx;
      margin-bottom: 15rpx;
      .allocMember {
        display: flex;
        align-items: center;
      }
      .share {
        margin-right: 20rpx;
      }
      .shareTip {
        display: flex;
        align-items: center;
      }
      .shareIcon {
        width: 50rpx;
        height: 50rpx;
      }
      .shareCodeIcon {
        width: 40rpx;
        height: 40rpx;
        margin-right: 10rpx;
      }
      .code {
        color: #999;
        width: 280rpx;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .teamUser {
        position: relative;
        width: 280rpx;
        height: 50rpx;
        border: 1px solid #ccc;
        border-radius: 8rpx;
        display: flex;
        align-items: center;
        .chooseName {
          margin-left: 15rpx;
          font-size: 28rpx;
          color: #999;
        }
        .arrow {
          position: absolute;
          top: 15rpx;
          right: 10rpx;
          width: 30rpx;
          height: 30rpx;
          transition: all 0.5s;
        }
        .arrowActive {
          transform: rotate(180deg);
        }
        .options {
          position: absolute;
          left: -20rpx;
          bottom: -250rpx;
          box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.3);
          height: 200rpx;
          width: 280rpx;
          padding: 20rpx;
          background-color: #fff;
          border-radius: 10rpx;
          transition: all 0.5s;
          transform: scale(0);
          .optionItem {
            display: flex;
            align-items: center;
            margin-bottom: 15rpx;
          }
        }

        .optionsActive {
          transform: scale(1);
        }
      }
    }
  }

  .dateContent {
    flex-direction: column;
    align-items: flex-start;
    .title {
      margin-right: 20rpx;
    }
    .dateBox {
      display: flex;
      align-items: center;
      margin-bottom: 10rpx;
      .dateInput {
        display: flex;
        align-items: center;
        .dateIcon {
          width: 50rpx;
          height: 50rpx;
          margin-right: 10rpx;
        }
        .date {
          display: flex;
          align-items: center;
          justify-content: space-between;
          color: #999;
          font-size: 26rpx;
          width: 300rpx;
          height: 70rpx;

          .clear {
            width: 70rpx;
            font-size: 35rpx;
          }
        }
      }
    }
  }
  .avatar {
    width: 70rpx;
    height: 70rpx;
    border-radius: 50%;
    margin-right: 10rpx;
  }
  .nickName {
    width: 70%;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
    color: #999;
  }
}
</style>

<style>
page {
  background-color: #fff;
  height: 100%;
}
</style>
